
package com.kugou.game.sdk.ui.activity;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnRegisterListener;
import com.kugou.game.sdk.interfaces.OnRequestValidateCodeV3Listener;
import com.kugou.game.sdk.observers.SmsMonitor;
import com.kugou.game.sdk.observers.SmsMonitor.onGetAuthCodeListener;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.SettingPref;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述:手机注册页面（一键注册）
 * 
 * @author liux
 * @since 2014-3-25 下午04:07:44
 */

public class RegisterByPhoneActivity extends BaseCommonTitleFragmentActivity {
    /**
     * 消息相关
     */
    private static final int MSG_REQUEST_VALIDATE_CODE = 1;

    private static final int MSG_REQUEST_VALIDATE_SUCCESS = 2;

    private static final int MSG_REQUEST_VALIDATE_FAILE = 3;

    private static final int MSG_AUTO_GET_VALIDATE_CODE = 4;

    private static final int MSG_USE_OUT_VALIDATE_TIMES = 5;

    private static final int MSG_START_LOADING = 6;

    private static final int MSG_START_COUNT_DOWN = 7;

    private static final int MSG_REQUEST_REGISTER = 8;

    private static final int MSG_REGISTER_SUCCESS = 9;// 注册成功

    private static final int MSG_REGISTER_FAILE = 10;// 注册失败

    private static final int MSG_NAME_ALREADY_EXIST = 11;// 注册名已存在

    /**
     * 弹出对话框相关
     */
    private static final int DIALOG_SHOW_REGISTER_TIPS = 10;

    private static final int DIALOG_SHOW_REGISTER_TEMPORARY = 20;

    /** 来自主界面的论坛入口 */
    private static final int DIALOG_SHOW_FROM_FORUM = 30;

    private static final int DIALOG_SHOW_LICENSE = 40;

    private static final int DIALOG_PHONE_ALREAD_REGISTER = 50;

    /**
     * 控件相关
     */

    private TextView mRegisterByAccText, mRegisterPhoneNumErrorTips, mRegisterErroeTips;

    private EditText mPhoneNumEdit, mValdateNumEdit;

    private Button mRequstValidateCodeBtn, mSubmitRegisterBtn;

    private LoadingView mLoadingView;

    private int mFrom;

    private ScrollView mLayoutScrollView;

    private CheckBox mPayAgreeKugouLicense;

    private TextView mPayAgreeKugouLicenseText;

    /**
     * 固定充值金额（来自于固定充值界面，用于判断注册成功后回跳转至固定充值界面）
     */
    private int fixedNum;

    private int mCountDownTimes = 60;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId = Rx.layout.kg_register_one_key_input_phone_activity;
        if (layoutId != 0) {
            setContentView(layoutId);
            setCommonTitle(Rx.string.kg_register_title);
            // 设置View界面
            initViews();
            // 设置界面显示
            showPhoneNumLayout();
            mFrom = getIntent().getIntExtra(FROM_ACTION_KEY, FROM_NORMAL);
            fixedNum = getIntent().getIntExtra(RechargeActivity.FIXED_MONEY_NUM, -1);

            if (mFrom == FROM_FORUM) {
                showMessageDialog(DIALOG_SHOW_FROM_FORUM);
            } else
            // 根据跳转来自页面做弹框逻辑
            if (mFrom == FROM_RECHARGE) {// 来自充值页面
                showMessageDialog(DIALOG_SHOW_REGISTER_TIPS);
            } else {// 正常情况或切换账号
                User userData = UserManager.getInstance().getCurrentUserInternal();
                if (userData != null) {
                    if (!userData.isRegistered()) {// 已登录，游客身份
                        showMessageDialog(DIALOG_SHOW_REGISTER_TEMPORARY);
                    }
                }
            }
        } else {
            showToast(Rx.string.kg_layout_not_found);
        }
    }

    /**
     * 根据获得到的本机号码自动填写到输入框中
     */
    private void showPhoneNumLayout() {
        String phonenum = readLocalPhoneNum();
        if (!TextUtils.isEmpty(phonenum)) {
            String phone = handlePrefix(phonenum);
            mPhoneNumEdit.setText(phone);
        }
    }

    /**
     * 处理提取的号码的前缀
     * 
     * @param phonenum
     * @return
     */
    private String handlePrefix(String phonenum) {
        if (phonenum.contains("+86")) {
            return phonenum.replace("+86", "");
        } else if (phonenum.startsWith("86")) {
            phonenum = phonenum.substring(2);
        }
        return phonenum;
    }

    /**
     * 读取本地手机号码
     * 
     * @return 手机号
     */
    private String readLocalPhoneNum() {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String phoneId = tm.getLine1Number();
        if (TextUtils.isEmpty(phoneId)) {
            // 发送统计-手机号是否自动读取成功
            StaticsManager.sendAutoReadPhoneStatics(StatCmd.CMD_RECOGNIZE_PHONE_NUM, 0);
            return "";
        } else {
            // 发送统计-手机号是否自动读取成功
            StaticsManager.sendAutoReadPhoneStatics(StatCmd.CMD_RECOGNIZE_PHONE_NUM, 1);
            if (isPhoneNumCorrect(handlePrefix(phoneId)))
                return phoneId;
            else
                return "";
        }
    }

    /**
     * 初始化页面
     */
    private void initViews() {
        mLayoutScrollView = (ScrollView) findViewById(Rx.id.kg_layout_scrollview);
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            int padding = (int) (90 * getResources().getDisplayMetrics().density);
            mLayoutScrollView.setPadding(padding, 0, padding, 0);
        }

        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loading);
        mLoadingView.setText("正在注册，请稍候...");

        mRegisterPhoneNumErrorTips = (TextView) findViewById(Rx.id.kg_register_account_tips);

        mRegisterErroeTips = (TextView) findViewById(Rx.id.kg_tv_register_phone_error_tip);

        mPhoneNumEdit = (EditText) findViewById(Rx.id.kg_et_register_input_phone_num);

        mValdateNumEdit = (EditText) findViewById(Rx.id.kg_et_register_input_validate_code);

        mValdateNumEdit.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    mRegisterErroeTips.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mValdateNumEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mRegisterErroeTips.setVisibility(View.GONE);
                }
            }
        });

        mPhoneNumEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {

                } else {
                    mRegisterPhoneNumErrorTips.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mPhoneNumEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = mPhoneNumEdit.getText().toString().trim();

                if (hasFocus) {
                    mRegisterPhoneNumErrorTips.setVisibility(View.GONE);
                } else {
                    if (!TextUtils.isEmpty(str)) {
                        checkPhoneNum();
                    }
                }
            }
        });

        // 请求验证码按钮
        mRequstValidateCodeBtn = (Button) findViewById(Rx.id.kg_btn_request_validate_code);
        mRequstValidateCodeBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                requestValidateCode();
            }

        });

        mSubmitRegisterBtn = (Button) findViewById(Rx.id.kg_btn_register_submit);
        mSubmitRegisterBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                sumbitRegister();
            }
        });

        // 用户名注册文本
        mRegisterByAccText = (TextView) findViewById(Rx.id.kg_tv_register_by_account);
        mRegisterByAccText.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 跳转到用户名注册页面
                gotoAccountRegister();
            }
        });

        // 用户协议
        int payAgreeKugouLicenseID = Rx.id.kg_cb_register_agree_protocol;
        mPayAgreeKugouLicense = (CheckBox) findViewById(payAgreeKugouLicenseID);
        int payAgreeKugouLicenseTextId = Rx.id.kg_tv_register_agree_protocol;
        mPayAgreeKugouLicenseText = (TextView) findViewById(payAgreeKugouLicenseTextId);
        mPayAgreeKugouLicenseText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageDialog(DIALOG_SHOW_LICENSE);
            }
        });

    }

    private void gotoAccountRegister() {
        // 跳转到用户名注册页面
        Intent intent = new Intent(RegisterByPhoneActivity.this, RegisterActivity.class);
        intent.putExtra(FROM_ACTION_KEY, mFrom);
        intent.putExtra(RechargeActivity.FIXED_MONEY_NUM, fixedNum);
        startActivity(intent);
        finish();
    }

    private void registerSuccess(String passwd, User user) {
        Intent intent = new Intent(RegisterByPhoneActivity.this, RegisterSuccessActivity.class);
        intent.putExtra(PHONE, mPhoneNumEdit.getText().toString().trim());
        intent.putExtra(PASSWORD, passwd);
        intent.putExtra(FROM_ACTION_KEY, mFrom);
        intent.putExtra(RechargeActivity.FIXED_MONEY_NUM, fixedNum);
        intent.putExtra(USER, user);
        startActivity(intent);
        finish();
    }

    /**
     * 提交注册
     */
    private void sumbitRegister() {
        if (!mPayAgreeKugouLicense.isChecked()) {
            showToast("请勾选《酷狗游戏通行证用户协议》");
            return;
        }

        // 隐藏软键盘
        hideSoftInput(this);

        if (checkPhoneNum()) {
            if (TextUtils.isEmpty(mValdateNumEdit.getText().toString())) {
                showToast("请输入验证码");
                return;
            }
            if (!NetWorkUtil.isNetworkAvailable(this)) {
                showToast("请检查您的网络连接");
                return;
            }

            Message message = Message.obtain();
            message.what = MSG_START_LOADING;
            message.obj = "正在注册，请稍候...";
            sendUiMessage(message);
            sendEmptyBackgroundMessageDelayed(MSG_REQUEST_REGISTER, 500);
        }

    }

    /**
     * 点击发送短信验证码按钮
     */
    private void requestValidateCode() {
        hideSoftInput(this);
        if (checkPhoneNum()) {
            if (!NetWorkUtil.isNetworkAvailable(this)) {
                showToast("请检查您的网络连接");
                return;
            }
            submitRequestValidateCode();
        }
    }

    /**
     * 检查手机号码
     */
    private boolean checkPhoneNum() {
        String text = mPhoneNumEdit.getText().toString().trim();
        if (isPhoneNumCorrect(text)) {
            return true;
        } else {
            mRegisterPhoneNumErrorTips.setText("请输入正确的手机号码！");
            mRegisterPhoneNumErrorTips.setVisibility(View.VISIBLE);
            return false;
        }
    }

    /**
     * 验证手机号码格式
     * 
     * @param phone
     * @return
     */
    private boolean isPhoneNumCorrect(String phone) {
        if (!TextUtils.isEmpty(phone)) {
            // 匹配11数字，并且13-19开头
            String regex = "^1[3-9]\\d{9}$";
            Pattern pt = Pattern.compile(regex);
            Matcher mc = pt.matcher(phone);
            return mc.matches();
        }
        return false;
    }

    /**
     * 请求验证码
     */
    private void submitRequestValidateCode() {
        Message message = Message.obtain();
        message.what = MSG_START_LOADING;
        message.obj = "正在请求验证码";
        sendUiMessage(message);
        sendEmptyBackgroundMessageDelayed(MSG_REQUEST_VALIDATE_CODE, 500);
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        final Message message = new Message();
        switch (msg.what) {
            case MSG_REQUEST_VALIDATE_CODE:
                int times = SettingPref.getInstance().getRemainValidateTimes();
                if (times > 0) {// 验证码请求剩余次数
                    mCountDownTimes = 60;

                    String phoneNum = mPhoneNumEdit.getText().toString().trim();
                    UserManager.getInstance().requestValidateCodeV3("", 1, phoneNum,
                            new OnRequestValidateCodeV3Listener() {
                                @Override
                                public void onFailed(String errorMsg, String errorCode) {
                                    message.what = MSG_REQUEST_VALIDATE_FAILE;
                                    Bundle bundle = new Bundle();
                                    bundle.putString("errorMsg", errorMsg);
                                    bundle.putString("errorCode", errorCode);
                                    message.setData(bundle);
                                }

                                @Override
                                public void onSuccess(String unixtime, String token) {
                                    message.what = MSG_REQUEST_VALIDATE_SUCCESS;

                                }
                            });
                } else {
                    sendEmptyUiMessage(MSG_USE_OUT_VALIDATE_TIMES);
                }
                break;
            case MSG_REQUEST_REGISTER:
                // 获取注册请求相关参数
                String mobile = mPhoneNumEdit.getText().toString().trim();
                String checkCode = mValdateNumEdit.getText().toString().trim();
                String tempName;
                User userData = UserManager.getInstance().getLastestUserDataOnSPAndSDcard();
                if (userData != null && !userData.isRegistered()) {
                    tempName = userData.getOpenId();
                } else {
                    tempName = "";
                }
                // 发送注册请求
                UserManager.getInstance().registerByPhone(mobile, tempName, checkCode,
                        new OnRegisterListener() {
                            @Override
                            public void onSuccess(User newUser) {
                                if (SDKControler.getGameType() == BaseSDKConfig.GAME_TYPE_ONLINE) {
                                    AppUtil.writeDataToSSO(newUser);
                                }
                                message.what = MSG_REGISTER_SUCCESS;
                                message.obj = newUser;
                            }

                            @Override
                            public void onFailed(String errorMsg, String errorCode) {
                                message.what = MSG_REGISTER_FAILE;
                                Bundle bundle = new Bundle();
                                bundle.putString("errorMsg", errorMsg);
                                bundle.putString("errorCode", errorCode);
                                message.setData(bundle);
                            }

                            @Override
                            public void onRecommendRegisterName(ArrayList<String> names) {
                                message.what = MSG_NAME_ALREADY_EXIST;
                                message.obj = names;
                            }

                        });
                break;
        }
        sendUiMessage(message);
    }

    int mTimes = 0;

    String mValidateCode = "";// 验证码

    SmsMonitor mMonitor;

    @Override
    public void handleUiMessage(Message msg) {
        switch (msg.what) {
            case MSG_START_LOADING:
                mLoadingView.setText((String) msg.obj);
                mLayoutScrollView.setVisibility(View.GONE);
                mLoadingView.setVisibility(View.VISIBLE);
                break;
            case MSG_START_COUNT_DOWN:
                mRequstValidateCodeBtn.setText(mCountDownTimes + "秒");
                mCountDownTimes--;
                if (mCountDownTimes > 0) {
                    sendEmptyUiMessageDelayed(MSG_START_COUNT_DOWN, 1000);
                } else {
                    mRequstValidateCodeBtn.setClickable(true);
                    mRequstValidateCodeBtn.setText("重新获取");
                }
                break;
            case MSG_REQUEST_VALIDATE_SUCCESS:
                sendEmptyUiMessage(MSG_START_COUNT_DOWN);
                mRequstValidateCodeBtn.setClickable(false);
                updateValidateLeftTimes();
                sendEmptyUiMessage(MSG_AUTO_GET_VALIDATE_CODE);
                break;
            case MSG_AUTO_GET_VALIDATE_CODE:
                mLoadingView.setText("验证码发送成功，正在自动识别...");
                // 自动识别获取响应的验证码
                mMonitor = new SmsMonitor(this);
                mMonitor.getAuthCode(8 * 1000, new onGetAuthCodeListener() {
                    public void onSuccess(String authCode) {
                        mValidateCode = authCode;
                        mValdateNumEdit.setText(mValidateCode);
                        // gotoSetPsdActivity();
                        showToast("自动识别成功，请提交注册！");
                        mLayoutScrollView.setVisibility(View.VISIBLE);
                        mLoadingView.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFailed(int errorCode) {
                        // gotoSetPsdActivity();
                        showToast("自动识别失败，请手动填写验证码!");
                        mLayoutScrollView.setVisibility(View.VISIBLE);
                        mLoadingView.setVisibility(View.GONE);
                    }

                });
                break;
            case MSG_REQUEST_VALIDATE_FAILE:
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                Bundle bundle = msg.getData();
                if (bundle == null) {
                    return;
                }
                String errorMsg = bundle.getString("errorMsg");
                String errorCode = bundle.getString("errorCode");

                if (!TextUtils.isEmpty(errorCode) && "44".equals(errorCode)) {// 手机号已注册
                    showAlreadyDialog();
                    return;
                }
                showToast(errorMsg);
                break;
            case MSG_USE_OUT_VALIDATE_TIMES:
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                showToast("您今天的验证次数已用完");
                break;
            case MSG_REGISTER_SUCCESS:
                User user = (User) msg.obj;
                registerSuccess(user.getPassword(), user);
                break;
            case MSG_NAME_ALREADY_EXIST:
                showAlreadyDialog();
                break;
            case MSG_REGISTER_FAILE:
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                mRegisterErroeTips.setText(msg.getData().getString("errorMsg"));
                mRegisterErroeTips.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void showAlreadyDialog() {
        final BaseConfirmDialog dialog = new BaseConfirmDialog(this);
        dialog.setMessage(getString(Rx.string.kg_phone_already_register));
        dialog.setCancelBtnVisibility(false);
        dialog.setOKBtnText("输入账号注册");
        dialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                gotoAccountRegister();

            }
        });
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    /**
     * 刷新验证码剩余次数
     */
    private void updateValidateLeftTimes() {
        int num = SettingPref.getInstance().getRemainValidateTimes();
        num--;
        SettingPref.getInstance().putRemainValidateTimes(num);
    }

    private void showMessageDialog(final int id) {
        final BaseConfirmDialog messageDialog = new BaseConfirmDialog(this);
        messageDialog.setCanceledOnTouchOutside(true);
        messageDialog.setCancelBtnVisibility(false);
        messageDialog.setOKBtnText("我知道了");
        messageDialog.setDialogHeight((int) (250 * getResources().getDisplayMetrics().density));
        switch (id) {
            case DIALOG_SHOW_REGISTER_TIPS:
                messageDialog.setMessage(getString(Rx.string.kg_register_tips));
                break;
            case DIALOG_SHOW_REGISTER_TEMPORARY:
                messageDialog.setMessage(getString(Rx.string.kg_register_temporary));
                break;
            case DIALOG_SHOW_FROM_FORUM:
                messageDialog.setMessage(getString(Rx.string.kg_register_forum_notice));
                break;
            case DIALOG_SHOW_LICENSE:
                messageDialog.setMessage(getString(Rx.string.kg_license_long));
                break;
            case DIALOG_PHONE_ALREAD_REGISTER:
                messageDialog.setMessage(getString(Rx.string.kg_phone_already_register));
                if (UserManager.getInstance().getCurrentUser() != null
                        && !UserManager.getInstance().getCurrentUser().isRegistered()) {
                    messageDialog.setMessage("尊敬的主人：\n您的手机号已经被注册过啦，建议您使用输入账号注册，以激活本地游客账号。");
                }

                messageDialog.setOKBtnText("输入账号注册");
                break;
        }

        messageDialog.setOKClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
                if (id == DIALOG_PHONE_ALREAD_REGISTER) {
                    gotoAccountRegister();
                }
            }
        });
        messageDialog.show();
    }

    @Override
    protected void onBackBtnClick() {
        exitRegisterPage();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitRegisterPage();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出注册界面
     */
    private void exitRegisterPage() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMonitor != null) {
            // 取消短信的所有监听，一定要调用
            mMonitor.unregisterMonitor();
        }
    }
}
